package com.junmoo.www.handler;

import com.alibaba.fastjson.JSON;
import com.junmoo.www.module.system.entity.SysUser;
import com.junmoo.www.utils.JwtTokenUtil;
import com.junmoo.www.utils.R;
import com.junmoo.www.utils.ResponseUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功处理类
 */
@Component
@Slf4j
@AllArgsConstructor
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private JwtTokenUtil jwtTokenUtil;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 组装JWT
        SysUser sysUser =  (SysUser) authentication.getPrincipal();
//        User sysUser =  (User) authentication.getPrincipal();
        String token = jwtTokenUtil.generateToken(sysUser);
        // 封装返回参数
        ResponseUtil.writeMsg(response, R.success("登录成功",token));
    }

}
